package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.web.admin.mapper.ApartmentInfoMapper;
import com.atguigu.lease.web.admin.mapper.FeeValueMapper;
import com.atguigu.lease.web.admin.mapper.GraphInfoMapper;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentDetailVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentItemVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentQueryVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentSubmitVo;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author liubo
 * @description 针对表【apartment_info(公寓信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class ApartmentInfoServiceImpl extends ServiceImpl<ApartmentInfoMapper, ApartmentInfo>
        implements ApartmentInfoService {

    @Autowired
    private ApartmentFacilityService apartmentFacilityService;

    @Autowired
    private FacilityInfoService facilityInfoService;

    @Autowired
    private ApartmentLabelService apartmentLabelService;

    @Autowired
    private LabelInfoService labelInfoService;

    @Autowired
    private ApartmentFeeValueService apartmentFeeValueService;

    @Autowired
    private FeeValueService feeValueService;

    @Autowired
    private FeeValueMapper feeValueMapper;

    @Autowired
    private GraphInfoService graphInfoService;

    @Autowired
    private GraphInfoMapper graphInfoMapper;


    // 分页查询公寓列表展示信息
    @Override
    public IPage<ApartmentItemVo> pageItem(Page<ApartmentItemVo> page, ApartmentQueryVo queryVo) {

        // 需要传一个page，否则会报 can't found IPage for args!
        return baseMapper.pageItem(page, queryVo);
    }

    @Override
    public void saveOrUpdateByItemVo(ApartmentSubmitVo apartmentSubmitVo) {
        // 多表关联 执行顺序：图片、公寓配套、公寓标签、公寓杂费值、基本信息
        // 如果要修改则要先删除，然后保存
        // 删除原有数据
        if (apartmentSubmitVo.getId() != null) {
            removeById(apartmentSubmitVo.getId());
        }
        // 保存
        // 继承关系，可以直接save,保存后即可获取子增键的ID
        saveOrUpdate(apartmentSubmitVo);
        Long itemId = apartmentSubmitVo.getId();

        graphInfoService.saveBatch(apartmentSubmitVo.getGraphVoList().stream().map(graphVo ->
        {
            GraphInfo graphInfo = GraphInfo.builder().itemId(itemId).itemType(ItemType.APARTMENT)
                    .url(graphVo.getUrl()).name(graphVo.getName())
                    .build();
            graphInfo.setCreateTime(new Date());
            return graphInfo;
        }).collect(Collectors.toList()));


        apartmentFacilityService.saveBatch(apartmentSubmitVo.getFacilityInfoIds().stream().map(facilityId ->
                {
                    ApartmentFacility facility = ApartmentFacility.builder().apartmentId(itemId).facilityId(facilityId).build();
                    facility.setCreateTime(new Date());
                    return facility;
                })
                .collect(Collectors.toList()));


        apartmentLabelService.saveBatch(apartmentSubmitVo.getLabelIds().stream().map(labelId ->
                {
                    ApartmentLabel label = ApartmentLabel.builder().apartmentId(itemId).labelId(labelId).build();
                    label.setCreateTime(new Date());
                    return label;
                })
                .collect(Collectors.toList()));

        apartmentFeeValueService.saveBatch(apartmentSubmitVo.getFeeValueIds().stream().map(feeValueId ->
                {
                    ApartmentFeeValue feeValue = ApartmentFeeValue.builder().apartmentId(itemId).feeValueId(feeValueId).build();
                    feeValue.setCreateTime(new Date());
                    return feeValue;
                })
                .collect(Collectors.toList()));
    }

    @Override
    public ApartmentDetailVo getDetailById(Long id) {

        ApartmentDetailVo detailVo = new ApartmentDetailVo();
        ApartmentInfo apartmentInfo = getById(id);

        if (apartmentInfo == null){
            throw new LeaseException(ResultCodeEnum.APARTMENT_NULL_ERROR);
        }

        BeanUtils.copyProperties(apartmentInfo, detailVo);

        // 分别从中间表或者主表中获取数据
        List<GraphInfo> list = graphInfoService.list(new LambdaQueryWrapper<GraphInfo>()
                .eq(GraphInfo::getItemId,id)
                .eq(GraphInfo::getItemType,ItemType.APARTMENT));
        List<GraphVo> graphVoList = list.stream().map(graphInfo ->
                GraphVo.builder().name(graphInfo.getName()).url(graphInfo.getUrl()).build()).collect(Collectors.toList());
        detailVo.setGraphVoList(graphVoList);
        List<Long> facilityIds = apartmentFacilityService.list(new LambdaQueryWrapper<ApartmentFacility>().eq(ApartmentFacility::getApartmentId, id))
                .stream().map(apartmentFacility -> apartmentFacility.getFacilityId()).collect(Collectors.toList());
        if (facilityIds.size() != 0){
            detailVo.setFacilityInfoList(facilityInfoService.listByIds(facilityIds));
        }
        List<Long> labelIds = apartmentLabelService.list(new LambdaQueryWrapper<ApartmentLabel>().eq(ApartmentLabel::getApartmentId, id))
                .stream().map(apartmentLabel -> apartmentLabel.getLabelId()).collect(Collectors.toList());
        if (labelIds.size() != 0) {
            detailVo.setLabelInfoList(labelInfoService.listByIds(labelIds));
        }

        // 联表查询储keyName

        detailVo.setFeeValueVoList(feeValueMapper.getFeeValueVoByApartmentId(id));

        return detailVo;
    }

    @Override
    @Transactional
    public void removeById(Long id) {
        super.removeById(id);
        graphInfoService.remove(new LambdaQueryWrapper<GraphInfo>()
                .eq(GraphInfo::getItemId, id)
                .eq(GraphInfo::getItemType, ItemType.APARTMENT));

        apartmentFacilityService.remove(new LambdaQueryWrapper<ApartmentFacility>()
                .eq(ApartmentFacility::getApartmentId, id));

        apartmentLabelService.remove(new LambdaQueryWrapper<ApartmentLabel>()
                .eq(ApartmentLabel::getApartmentId, id));

        apartmentFeeValueService.remove(new LambdaQueryWrapper<ApartmentFeeValue>()
                .eq(ApartmentFeeValue::getApartmentId, id));

    }
}




